package com.hhc.netty;

import android.util.Log;

import com.example.administrator.androidros.utils.AgentSharedPreferences;
import com.example.administrator.androidros.utils.AppApplication;

import org.greenrobot.eventbus.EventBus;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * Created by huhaichao on 2018/3/5.
 */

public class NettyClientHandler extends SimpleChannelInboundHandler<NettyBaseMsg>  {
    private static final String TAG = "hhc";
    private int send_count=0;
    private int receive_count=0;
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case WRITER_IDLE:
                    NettyPingMsg nettyPingMsg = new NettyPingMsg();
                    nettyPingMsg.setType(NettyMsgType.CLIENT);
//                    nettyPingMsg.setType(NettyMsgType.DEVICE);
//                    nettyPingMsg.setMemberId(AgentSharedPreferences.getLastLoginId(AppApplication.getContext()));
                    nettyPingMsg.setClientId(AgentSharedPreferences.getMemberInfo(AppApplication.getContext()).getMemberTelephone());

//                    nettyPingMsg.setDeviceId(NotificationFragment.deviceId);
                    ctx.writeAndFlush(nettyPingMsg);
                    Log.e("心跳包", "send心跳包"+(send_count++));
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 收到数据时
     */
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, NettyBaseMsg msg) throws Exception {
        if(msg!=null){
            switch (msg.getNettyMsgType())
            {
                case PING:
                    Log.e("心跳包", "receive心跳包"+(receive_count++));
                    break;
                case OPERATION:
                    Log.e(TAG, "======================");
                    NettyOperationMsg nettyOperationMsg = (NettyOperationMsg) msg;
                    Log.e(TAG, "信息：" + nettyOperationMsg.getMessage());
                    Log.e(TAG, "======================");
                    break;
                case ASK_STATUS:
                    break;
                case REPLY_STATUS:
                    //移动控制端（有）
                    //收到：家电状态
                    EventBus.getDefault().post(msg);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 建立连接成功时执行一次
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Log.e(TAG, "channelActive: 连接成功");
        NettyClient.getInstance().setConnectState(NettyClient.CONNECTED);
        //上线信息
        NettyOnlineMsg nettyOnlineMsg = new NettyOnlineMsg();
        nettyOnlineMsg.setNettyMsgType(NettyMsgType.ONLINE);
        //设置上线类型(和终端区别)
        nettyOnlineMsg.setType(NettyMsgType.CLIENT);
        nettyOnlineMsg.setClientId(AgentSharedPreferences.getMemberInfo(AppApplication.getContext()).getMemberTelephone());
        ctx.writeAndFlush(nettyOnlineMsg);
    }

    /**
     * 连接断开时
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        NettyClient.getInstance().setConnectState(NettyClient.DISCONNECTION);
        Log.e(TAG, "连接已断开,重新连接...");
        NettyClient.getInstance().doConnect();
    }
}
